import ajax from '@/utils/ajax'
import { message } from 'ant-design-vue'

const questionsTypeMap = {
  '0': 'radio', // 单选
  '1': 'checkbox', // 多选
  '2': 'blank', // 填空
  // '2': 'blankForm', // 填空
  '3': 'sort', // 排序
  '4': 'forcedChoice',
  '5': 'tableQuestion',
  '7': 'jsCoding',
  '8': 'htmlCoding',
  '9': 'ask'
}

const dealCode = function(res) {
  // console.log('触发dealCode', res)
  if (res.code === 20006) {
    window.location.href = '/questionnaire/403'
  } else if (res.code === 403) {
    window.location.href = '/questionnaire/404'
  } else if (res.code === 402) {
    window.location.href = '/questionnaire/completed'
  } else if (res.code === 404) {
    window.location.href = '/questionnaire/404'
  }
}

const requestTask = function({ id, code, phone, username } = {}) {
  return ajax.get(`/consultant/questionnaires/tasks/${id}.do`, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    params: {
      code,
      phone,
      username
    }
  }).then(res => {
    // console.log('res', res)
    if (res.code && res.code === 200) {
      return res.result
    } else {
      message.error(res.message)
    }
  }).catch(err => {
    // console.log(err, '----')
    dealCode(err)
  })
}

const handleQuestion = function(resData) {
  const data = resData
  let questionsList = []
  questionsList = data.map(item => {
    if (item.choices && item.choices.length) {
      // console.log('item.choices', item.choices)
      item.choices.forEach(c => {
        if (c.type === 1) {
          c.isBlank = true
        }
        if (c.isExclude === 1) {
          c.isExclude = true
        }
      })
    }
    const questionType = questionsTypeMap[item.type]
    let questionContent = item.choices
    if (['tableQuestion', 'forcedChoice'].includes(questionType) && item.choices && item.choices.length > 0) {
      if (item.choices[0].content) {
        questionContent = JSON.parse(item.choices[0].content)
      } else {
        questionContent = {}
      }
    }
    const obj = {
      isShow: item.isShow, // 是否展示该题目，用于跳题逻辑
      questionNumber: item.number, // 题目序号，用于跳题逻辑
      questionId: item.id,
      questionType: questionType, // 题型
      questionName: item.content, // 题干
      questionDesc: item.questionDesc, // 题目描述
      requiredFlag: !!item.required, // 是否必填
      questionContent: questionContent,
      questionMin: item.minChoices,
      questionMax: item.maxChoices,
      componentName: questionType,
      error: item.error || ''
    }
    return obj
  })
  // console.log('questionsList', questionsList)
  return questionsList
}

const handleQuestionnaireData = function(data) {
  // console.log(data)
  const { content, id, name, taskUserId } = data
  const questionnaies = data.sections.map(item => {
    const { id, number, title, questions } = item
    const obj = {
      id,
      number,
      title,
      questions: handleQuestion(questions)
    }
    return obj
  })
  // console.log('questionnaies', questionnaies)
  return {
    content,
    id,
    name,
    taskUserId,
    sections: questionnaies
  }
}
export default {
  handleQuestionnaireData,
  // 获取问卷名称
  getQuestionnaireName({ id }) {
    return ajax.get(`/consultant/questionnaires/tasks/${id}/name.do`, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }).then(res => {
      if (res.code && res.code === 200) {
        return res.result
      } else {
        message.error(res.message)
      }
    }).catch(res => {
      dealCode(res)
      message.error(res.message || res)
    })
  },
  // 获取问卷
  async getQuestionnaire({ code, id, phone, username }) {
    const res = await requestTask({ code, id, phone, username })
    // console.log('res', JSON.stringify(res))
    const data = handleQuestionnaireData(res)
    return data
  },

  // 获取验证码
  requestCode(phone) {
    return ajax.get('/consultant/questionnaires/code.do', {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      params: {
        phone,
      },
    }).then(res => {
      if (!(res.code && res.code === 200)) {
        message.error(res.message)
      }
      return res
    })
  },

  submit({ id, answers, phone, taskUserId, username } = {}) {
    // console.log('id, answers, phone, taskUserId, username', id, answers, phone, taskUserId, username)
    return ajax.post(`/consultant/questionnaires/tasks/${id}.do`, {
      data: {
        answers,
        phone,
        taskUserId,
        username
      }
    }).then(res => {
      if (res.code === 200) {
        window.location.href = '/questionnaire/complete'
      }
    }).catch(err => {
      dealCode(err)
    })
  }
}
